package com.way;

import java.util.concurrent.*;

/**
 * 线程池自定义拒绝策略
 *
 * @author: 魏彪
 */
public class Test07 {

    public static void main(String[] args) {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                8,
                16,
                15,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(10),
                Executors.defaultThreadFactory(),
                new MyRejectedExecutionHandler()
                // new ThreadPoolExecutor.CallerRunsPolicy()
        );

        // threadPoolExecutor.execute(() -> System.out.println(Thread.currentThread().getName()));
        for (int i = 0; i < 20000; i++) {
            threadPoolExecutor.execute(new MyRunnable(i));
        }

        threadPoolExecutor.shutdown();
    }

    static class MyRunnable implements Runnable {

        private final int i;

        public MyRunnable(int i) {
            this.i = i;
        }

        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + "===============" + i);
        }
    }

    static class MyRejectedExecutionHandler implements RejectedExecutionHandler {

        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
            // 如果任务队列满了，就超时等待，可以设置一个时间
            try {
                executor.getQueue().offer(r, 60, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
